#include <iostream>
#include <memory>
#include "TcpServer.hpp"
#include "Err.hpp"
#include "Protocol.hpp"

void Usage(std::string arg)
{
    std::cout << "\n Usage: \n\t" << arg << " port"
              << "\n\t" << std::endl;
}

bool cal(const Request &req, Response &res)
{
    // 将计算结果得到res中
    res._result = OK;
    res._resCode = OK;
    switch (req._op)
    {
    case '+':
        res._result = req._x + req._y;
        break;
    case '-':
        res._result = req._x - req._y;
        break;
    case '*':
        res._result = req._x * req._y;
        break;
    case '/':
    {
        if (req._y == 0)
        {
            res._result = 0;
            res._resCode = DIV_ERR;
        }
        else
        {
            res._result = req._x / req._y;
        }
    }
    break;
    case '%':
    {
        if (req._y == 0)
        {
            res._result = 0;
            res._resCode = MOD_ERR;
        }
        else
        {
            res._result = req._x % req._y;
        }
    }
    break;
    default:
        res._resCode = OP_ERR;
        res._result = 0;
        break;
    }
}

// 处理读到的数据
void calServer(Connection *con)
{
    // 获得一个有效的报文
    std::string onePackage;
    while (ParseOnePackage(con->inbuffer, &onePackage))
    {
        // 此时获取了  "connect_len"\r\n"text"\r\n  去掉报头
        std::string package;
        if (!deLength(onePackage, &package))
        {
            return;
        }
        std::cout << "去掉报头的数据为：" << package << std::endl;
        // 进行反序列化
        Request req; // 请求
        req.deSerialize(package);
        Response res;
        // 进行计算任务
        cal(req, res);
        // 对结果进行序列化
        std::string text;
        res.Serialize(&text);
        con->outbuffer += enLength(text); // 添加报头并加入到输出缓冲区当中
        std::cout << "------------result------------: " << con->outbuffer << std::endl;
    }
    // 直接发送
    if (con->_Send)
    {
        con->_Send(con);
    }
}

// ./epollserver 8080
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    std::unique_ptr<TcpServer> utsv(new TcpServer(calServer, atoi(argv[1])));
    utsv->InitServer(); // 初始化服务器
    utsv->Dispatch();   // 事件派发

    return 0;
}